package com.git.smp.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.git.smp.cache.DataDictionaryCache;
import com.git.smp.core.PageRequest;
import com.git.smp.core.ResponseMessage;
import com.git.smp.dao.EsbEnvironmentMapper;
import com.git.smp.dao.LogDetailMapper;
import com.git.smp.dao.SmpEnvironmentMapper;
import com.git.smp.dao.SrvServiceLogDataMapper;
import com.git.smp.dao1.LogDetailMapper1;
import com.git.smp.dao1.SrvServiceLogDataMapper1;
import com.git.smp.dao2.LogDetailMapper2;
import com.git.smp.dao2.SrvServiceLogDataMapper2;
import com.git.smp.dao3.LogDetailMapper3;
import com.git.smp.dao3.SrvServiceLogDataMapper3;
import com.git.smp.entity.ApplyEnvironment;
import com.git.smp.entity.EsbEnvironment;
import com.git.smp.entity.LogDetail;
import com.git.smp.entity.LogDetailKey;
import com.git.smp.entity.NetWork;
import com.git.smp.entity.SmpEnvironment;
import com.git.smp.entity.SrvServiceLogDataExtend;
import com.git.smp.entity.SrvServiceLogDataWithBLOBs;
import com.git.smp.utils.EBCDICTransUtil;
import com.git.smp.utils.ExecuteShellUtil;
import com.git.smp.utils.HexBin;
import com.git.smp.utils.ObjectUtil;
import com.git.smp.utils.StringCompress;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcraft.jsch.JSchException;

@RestController
@RequestMapping("/environment")
public class SmpEnvironmentController {
	
	Logger logger = LoggerFactory.getLogger(SmpEnvironmentController.class);
	
	@Autowired
	SmpEnvironmentMapper smpEnvironmentMapper;
	
	@Autowired 
	SrvServiceLogDataMapper srvServiceLogDataMapper;
	
	@Autowired 
	SrvServiceLogDataMapper1 srvServiceLogDataMapper1;
	
	@Autowired 
	SrvServiceLogDataMapper2 srvServiceLogDataMapper2;
	
	@Autowired 
	SrvServiceLogDataMapper3 srvServiceLogDataMapper3;
	
	
	
	@Autowired 
	LogDetailMapper logDetailMapper;
	
	@Autowired
	LogDetailMapper1 logDetailMapper1;
	
	@Autowired
	LogDetailMapper2 logDetailMapper2;
	
	@Autowired
	LogDetailMapper3 logDetailMapper3;
	
	@Autowired
	EsbEnvironmentMapper esbEnvironmentMapper;
	
	@Autowired
	private HttpServletRequest request;
	

	/**
	 * 分页查询环境列表信息
	 * @param pageRequest
	 * @return
	 */
	@RequestMapping("/getEnvironmentInfoByPage")
	public ResponseMessage<PageInfo<SmpEnvironment>> getEnvironmentInfoByPage(
			@RequestBody PageRequest<SmpEnvironment> pageRequest){
		
		ResponseMessage<PageInfo<SmpEnvironment>> responseMessage = new ResponseMessage<PageInfo<SmpEnvironment>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("环境信息列表查询成功！");
		
		SmpEnvironment smpEnvironment = pageRequest.getBody();
		PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
		List<SmpEnvironment> listSmpEnvironment = smpEnvironmentMapper.getEnvironmentInfoByPage(smpEnvironment);
		
		if(listSmpEnvironment.size() == 0) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("未查询到符合条件的环境信息！");
		}
		PageInfo<SmpEnvironment> pageInfo = new PageInfo<SmpEnvironment>(listSmpEnvironment, pageRequest.getPageSize());
		responseMessage.setExtend(pageInfo);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	
	
	/**
	 * 分页查询环境列表信息
	 * @param pageRequest
	 * @return
	 */
	@RequestMapping("/getEnvironmentInfoByPageNew")
	public ResponseMessage<PageInfo<SmpEnvironment>> getEnvironmentInfoByPageNew(
			@RequestBody PageRequest<SmpEnvironment> pageRequest){
		
		ResponseMessage<PageInfo<SmpEnvironment>> responseMessage = new ResponseMessage<PageInfo<SmpEnvironment>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("环境信息列表查询成功！");
		
		SmpEnvironment smpEnvironment = pageRequest.getBody();
		PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
		
		String systemResponsibleMan = request.getHeader("userName");
		smpEnvironment.setSystemResponsibleMan(systemResponsibleMan);
		List<SmpEnvironment> listSmpEnvironment = smpEnvironmentMapper.getEnvironmentInfoByPageNew(smpEnvironment);
		
		if(listSmpEnvironment.size() == 0) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("未查询到符合条件的环境信息！");
		}
		PageInfo<SmpEnvironment> pageInfo = new PageInfo<SmpEnvironment>(listSmpEnvironment, pageRequest.getPageSize());
		responseMessage.setExtend(pageInfo);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	
	/**
	 * 查询单条环境信息
	 * @param smpEnvironment
	 * @return
	 */
	@RequestMapping("/getEnvironmentInfo")
	public ResponseMessage<SmpEnvironment> getEnvironmentInfo(
			@RequestBody SmpEnvironment smpEnvironment){
		ResponseMessage<SmpEnvironment> responseMessage = new ResponseMessage<SmpEnvironment>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("环境信息查询成功！");
		
		SmpEnvironment smpEnvironmentInfo = smpEnvironmentMapper.selectByPrimaryKey(smpEnvironment);
		if(smpEnvironmentInfo == null) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("未查询到环境信息！");
		}
		
		responseMessage.setExtend(smpEnvironmentInfo);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	
	@RequestMapping("/getSystemHistoryAddr")
	public ResponseMessage<List<String>> getSystemHistoryAddr(
			@RequestBody ApplyEnvironment applyEnvironment){
		ResponseMessage<List<String>> responseMessage = new ResponseMessage<List<String>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("系统环境历史信息查询成功！");
		SmpEnvironment smpEnvironment = new SmpEnvironment();
		ObjectUtil.copyBeans(applyEnvironment, smpEnvironment);
		
		List<String> listAddr = smpEnvironmentMapper.getSystemHistoryAddr(smpEnvironment);
		if(listAddr == null) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("未查询到环境信息！");
		}
		responseMessage.setExtend(listAddr);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	  
	  
	  
	  
	/**
	 * 分页查询交易跟踪
	 * @param pageRequest
	 * @return
	 */
	  @RequestMapping("/getBusinessFollowByPage")
	  public ResponseMessage<PageInfo<SrvServiceLogDataWithBLOBs>> getBusinessFollowByPage(
			  @RequestBody PageRequest<SrvServiceLogDataExtend> pageRequest
	    	) {
	    	ResponseMessage<PageInfo<SrvServiceLogDataWithBLOBs>> responseMessage = new ResponseMessage<PageInfo<SrvServiceLogDataWithBLOBs>>();
	        responseMessage.setCode("0000");
	        responseMessage.setMessage("查询交易跟踪成功！");
	        
	        SrvServiceLogDataExtend srvServiceLogDataExtend =pageRequest.getBody();
	        
	        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
	        List<SrvServiceLogDataWithBLOBs> listSrvServiceLogDataWithBLOBs = null;
	        if("01".equals(srvServiceLogDataExtend.getTestEnvir())) {
	        	listSrvServiceLogDataWithBLOBs = srvServiceLogDataMapper.getBusinessFollowByPage(srvServiceLogDataExtend);
	        }else if("02".equals(srvServiceLogDataExtend.getTestEnvir())){
	        	listSrvServiceLogDataWithBLOBs = srvServiceLogDataMapper1.getBusinessFollowByPage(srvServiceLogDataExtend);
	        }else if("03".equals(srvServiceLogDataExtend.getTestEnvir())){
	        	listSrvServiceLogDataWithBLOBs = srvServiceLogDataMapper2.getBusinessFollowByPage(srvServiceLogDataExtend);
	        }
	        else if("04".equals(srvServiceLogDataExtend.getTestEnvir())){
	        	listSrvServiceLogDataWithBLOBs = srvServiceLogDataMapper3.getBusinessFollowByPage(srvServiceLogDataExtend);
	        }
	     
	        if (listSrvServiceLogDataWithBLOBs == null) {
	            responseMessage.setCode("0001");
	            responseMessage.setMessage("未查询到交易跟踪信息！");
	        }
	        PageInfo<SrvServiceLogDataWithBLOBs> pageInfo = new PageInfo<SrvServiceLogDataWithBLOBs>(listSrvServiceLogDataWithBLOBs, pageRequest.getPageSize());
	        responseMessage.setExtend(pageInfo);
	        logger.info(responseMessage.getMessage());
	        return responseMessage;
	    }
	  
	  
	  /**
	   * 交易详情
	   * @param seqServiceLog
	   * @return
	   */
	  @RequestMapping("/getBusinessFollowByLog")
	  public ResponseMessage<SrvServiceLogDataWithBLOBs> getBusinessFollowByLog(
			  @RequestParam(value = "seqServiceLog", defaultValue = "") String seqServiceLog,
			  @RequestParam(value = "testEnvir", defaultValue = "") String testEnvir
	    	) {
	    	ResponseMessage<SrvServiceLogDataWithBLOBs> responseMessage = new ResponseMessage<SrvServiceLogDataWithBLOBs>();
	        responseMessage.setCode("0000");
	        responseMessage.setMessage("查询交易跟踪成功！");
	        
	        SrvServiceLogDataWithBLOBs srv = null;
	        
	        if("01".equals(testEnvir)) {
	        	srv = srvServiceLogDataMapper.selectByPrimaryKey(seqServiceLog);
	        }else if("02".equals(testEnvir)) {
	        	srv = srvServiceLogDataMapper1.selectByPrimaryKey(seqServiceLog);
	        }else if("03".equals(testEnvir)){
	        	srv = srvServiceLogDataMapper2.selectByPrimaryKey(seqServiceLog);
	        }else if("04".equals(testEnvir)){
	        	srv = srvServiceLogDataMapper3.selectByPrimaryKey(seqServiceLog);
	        }
	        		
	        		
	        if (srv == null) {
	            responseMessage.setCode("0001");
	            responseMessage.setMessage("未查询到交易跟踪信息！");
	        }
	        responseMessage.setExtend(srv);
	        logger.info(responseMessage.getMessage());
	        return responseMessage;
	    }
	  
	  
	  
	  /**
	   * 交易详情日志
	   * @param seqServiceLog
	   * @return
	   * @throws IOException 
	   */
	  @RequestMapping("/getFollowByLog")
	  public ResponseMessage<List<Map>> getFollowByLog(
			  @RequestBody LogDetailKey key
	    	) throws IOException {
	    	ResponseMessage<List<Map>> responseMessage = new ResponseMessage<List<Map>>();
	        responseMessage.setCode("0000");
	        responseMessage.setMessage("查询交易日志成功！");
	        
	        List<LogDetail>  logDetailList = null;
	        if("01".equals(key.getTestEnvir())) {
	        	logDetailList = logDetailMapper.getFollowByLog(key.getSeqServiceLog());
	        }else if("02".equals(key.getTestEnvir())){
	        	logDetailList = logDetailMapper1.getFollowByLog(key.getSeqServiceLog());
	        }else if("03".equals(key.getTestEnvir())){
	        	logDetailList = logDetailMapper2.getFollowByLog(key.getSeqServiceLog());
	        }else if("04".equals(key.getTestEnvir())){
	        	logDetailList = logDetailMapper3.getFollowByLog(key.getSeqServiceLog());
	        }
	        
	         
	        
	        if (logDetailList == null) {
	            responseMessage.setCode("0001");
	            responseMessage.setMessage("未查询到交易日志信息！");
	        }
	        
	        List<Map>  list = new ArrayList<>();
	        
	        for (LogDetail LogDetail2 : logDetailList) {
	        	logger.info(LogDetail2.getMsg());
	        	//解码
	        	String decode = "";
	        	if(LogDetail2.getMsg() != null && !"".equals(LogDetail2.getMsg())) {
	        		decode = StringCompress.gunzip(LogDetail2.getMsg());
	        	}
	        	
	        	Map m = new HashMap<>();
	
				//XML
				if(decode.indexOf("<![CDATA[")>-1) {
					try {
						String b = decode.substring(decode.indexOf("<Transaction>"));
						String c = b.substring(0, b.indexOf("</Transaction>")+14);
						Document doc = DocumentHelper.parseText(c);
						
						ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
						OutputFormat format = OutputFormat.createPrettyPrint();
						format.setSuppressDeclaration(true);
						format.setNewLineAfterDeclaration(false);
						XMLWriter xmlWriter = new XMLWriter(arrayOutputStream,format);
						xmlWriter.write(doc);
						xmlWriter.close();
						
						m.put("msg", arrayOutputStream.toString().replaceFirst("\n", ""));
						m.put("type", "xml");
						arrayOutputStream.close();
						
						
					} catch (DocumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}else {//JSON或其他
					try {
						Document doc = DocumentHelper.parseText( decode);
						String jsonString = doc.getStringValue();
						
						ObjectMapper mapper = new ObjectMapper();
						Map map = mapper.readValue(jsonString, Map.class);
						
						DefaultPrettyPrinter defaultPrettyPrinter = new DefaultPrettyPrinter();
						String msg = mapper.writer(defaultPrettyPrinter).writeValueAsString(map);
						m.put("msg", msg); 
						m.put("type", "json");
					} catch (Exception e) {
						//ebcdic报文
						try {
						   	logger.info("报文："+decode);
						   	String xmlString = new String(EBCDICTransUtil.EBCDICtoASIIC(HexBin.decode(decode)),"GBK");
						   	logger.info("转换后报文："+xmlString);
						   	Document doc = DocumentHelper.parseText(xmlString.trim());	
						   	
						   	ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
							OutputFormat format = OutputFormat.createPrettyPrint();
							format.setSuppressDeclaration(true);
							format.setNewLineAfterDeclaration(false);
							XMLWriter xmlWriter = new XMLWriter(arrayOutputStream,format);
							xmlWriter.write(doc);
							xmlWriter.close();
							m.put("msg", arrayOutputStream.toString().replaceFirst("\n", ""));
							m.put("type", "xml");
							arrayOutputStream.close();
						}catch (Exception e1) {
							logger.error("",e1);
							m.put("msg", decode);
							m.put("type", "");
						}
					}
				}
				
				list.add(m);
			}
	        
	        responseMessage.setExtend(list);
	        logger.info(responseMessage.getMessage());
	        return responseMessage;
	    }
	  
	  
	  
	  
	  @RequestMapping("/executeCommand")
	  public ResponseMessage<?> executeCommand(@RequestBody NetWork netWork){
		  ResponseMessage<?> responseMessage = new ResponseMessage();
		  responseMessage.setCode("0000");
		  netWork.setEsbAddr(DataDictionaryCache.getItemName("SMP0016", netWork.getEsbAddr()));
		  ExecuteShellUtil executeShellUtil = new ExecuteShellUtil();
		  
		  
		  
		  
		  try {
			  EsbEnvironment esbEnvironment =  esbEnvironmentMapper.selectByPrimaryKey(netWork.getEsbAddr());
			executeShellUtil.init(netWork.getEsbAddr(),Integer.parseInt(esbEnvironment.getPort()), esbEnvironment.getUserName(), esbEnvironment.getPasswd());
		} catch (JSchException e) {
			responseMessage.setCode("0001");
			responseMessage.setMessage(e.getMessage());
			e.printStackTrace();
		}
		  if("01".equals(netWork.getCommand())) {
			  try {
				  responseMessage.setMessage(executeShellUtil.execCmd("ping -c 3 "+netWork.getSystemCurrentAddr()));
			} catch (Exception e) {
				responseMessage.setCode("0001");
				responseMessage.setMessage(e.getMessage());
				e.printStackTrace();
			}
		  }else {
			  try {
				  responseMessage.setMessage(executeShellUtil.execCmd("echo \"\" | telnet "+netWork.getSystemCurrentAddr()+ " " + netWork.getPort()));
			} catch (Exception e) {
				responseMessage.setCode("0001");
				responseMessage.setMessage(e.getMessage());
				e.printStackTrace();
			}
		  }
		  executeShellUtil.close();
		  logger.info(responseMessage.getMessage());
		  return responseMessage;
	  }
	  
}
